import axios from './myAxios'
import {bus} from './brothersBus'

/**
 * 导出com对象模块
 * @type {{}}
 */
let com = {}
com.basePath = process.env.API_ROOT
com.uploadUrl = process.env.UPLOAD_ROOT
// 获取自己域名
com.domain = window.location.origin

// 获取localStorage
com.getStore = function (name) {
  return localStorage.getItem(name)
}
// 存储localStorage
com.setStore = function (name, data) {
  localStorage.setItem(name, data)
}

/**
 * 使用axios完成http请求
 * @type {number}
 */
com.axio = axios

// 时间格式化
com.formatDate = function (time) {
  let date = new Date(time)
  let fmt = 'yyyy-MM-dd hh:mm:ss'
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + ''
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
    }
  }
  return fmt
}

function padLeftZero(str) {
  return ('00' + str).substr(str.length)
}

/**
 * 弹窗
 * @param obj
 */

com.alert = function (obj) {
  bus.$emit('showDialog', obj)
}

/**
 * 页面刷新
 * @param vueThis
 */
com.reload = function (vueThis) {
  // 先定义一个空页面
  const NewPage = '_empty' + '?time=' + new Date().getTime() / 1000
  // 之后将页面push进去
  vueThis.$router.push(NewPage)
  // 再次返回上一页即可
  setTimeout(() => {
    vueThis.$router.go(-1)
  }, 50)
}
// 获取区域回显
const countArr = function (str) {
  const len = str.length
  let arr = []
  if (len > 6) {
    arr.push(str.slice(0, 2))
    arr.push(str.slice(0, 4))
    arr.push(str.slice(0, 6))

    let other = (len - 6) / 3
    for (let i = 1; i <= other; i++) {
      arr.push(str.slice(0, 6 + i * 3))
    }
  } else {
    for (let i = 1; i <= parseInt(len / 2); i++) {
      arr.push(str.slice(0, i * 2))
    }
  }
  return arr
}
com.getAreaCodeArr = countArr

// 提供遮罩
com.mask = function () {
  let dom = document.createElement('div')
  dom.className += 'g-mask'
  dom.innerHTML = '<p></p>'
  document.body.appendChild(dom)
}

com.unmask = function () {
  let body = document.querySelector('body')
  body.removeChild(body.querySelector('.g-mask'))
}

com.checkMobile = function (value) {
  if (!/^1[34578]\d{9}$/.test(value)) {
    return false
  }
  return true
}
com.checkPhone = function (val) {
  if (/\d{3}-\d{8}|\d{4}-\d{7}/.test(val) || /^1[34578]\d{9}$/.test(val)) {
    return true
  }
  return false
}

/**
 * 数组去重
 */
com.uniqueArr = function (arr) {
  const newArr = []
  const selectObj = {}
  arr.forEach(function (v, i) {
    if (!selectObj[v]) {
      newArr.push(v)
    }
    selectObj[v] = true
  })
  return newArr
}
export default com
